package com.example.ljw.frescowallpaper.view;

import android.app.WallpaperManager;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.ljw.frescowallpaper.R;
import com.example.ljw.frescowallpaper.base.BaseActivity;
import com.example.ljw.frescowallpaper.bean.UserBean;
import com.example.ljw.frescowallpaper.config.Constants;
import com.example.ljw.frescowallpaper.helper.HttpURLConnHelper;
import com.example.ljw.frescowallpaper.helper.SDCardHelper;
import com.example.ljw.frescowallpaper.utils.PreUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.QueryListener;
import cn.bmob.v3.listener.UpdateListener;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.tencent.qq.QQ;
import okhttp3.Call;

import static android.R.attr.onClick;

public class Details extends BaseActivity implements View.OnClickListener{
    private ImageView imageView_detail;
    private Button wallpaper,save,star,share,back;
    private TextView favorite_textview;
    private Bitmap bitmap;
    private WallpaperManager wallpaperManager;
    private HashMap<String,Object> hashMap = new HashMap<String, Object>();

    private String url;

    //要取消收藏的位置
    private int deletePosition = 0;
    private UserBean user;
    private List<String> favariteList;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_details);
        ShareSDK.initSDK(this);
        hashMap.put("ShareByAppClient","true");
        Intent intent=getIntent();
        url=intent.getStringExtra("URL");
        Log.e("Tag",""+url);


        initView();

    }

    @Override
    protected void onResume() {
        super.onResume();
        loadFavoriteData();
    }

    private void initView() {
        favorite_textview = (TextView) findViewById(R.id.favorite_textview);
        imageView_detail= (ImageView) findViewById(R.id.imageView_detail);
        wallpaper= (Button) findViewById(R.id.wallpaper);
        wallpaper.setOnClickListener(this);
        save= (Button) findViewById(R.id.save);
        save.setOnClickListener(this);
        star= (Button) findViewById(R.id.star);
        //加载原来收藏信息
//        loadFavoriteData();
        star.setOnClickListener(this);
        share= (Button) findViewById(R.id.share);
        share.setOnClickListener(this);
        back= (Button) findViewById(R.id.btn_back);
        back.setOnClickListener(this);


        Glide.with(this)
                .load(url)
                .into(imageView_detail);

        imageView_detail.setDrawingCacheEnabled(true);




    }
//    private void delete(String url){
//        //获取objectid
//        String objectId = PreUtils.readStrting(Details.this, Constants.KEY_OF_OBJECTID);
//        favariteList = new ArrayList<>();
//        user = new UserBean();
//        BmobQuery<UserBean> query = new BmobQuery<>();
//        query.getObject(objectId, new QueryListener<UserBean>() {
//            @Override
//            public void done(UserBean userBean, BmobException e) {
//                favariteList = userBean.getFavorite();
//            }
//        });
//        for (String mylist:favariteList){
//            if (mylist.equals(url)){
//                favariteList.remove(url);
//                favorite_textview.setText("收藏");
//                return;
//            }
//        }
//    }

    private void loadFavoriteData() {
        //获取objectid
        String objectId = PreUtils.readStrting(Details.this, Constants.KEY_OF_OBJECTID);
        if (objectId.equals("8BkXsLLs")){

        }else {
            favariteList = new ArrayList<>();
            user = new UserBean();
            BmobQuery<UserBean> query = new BmobQuery<>();
            query.getObject(objectId, new QueryListener<UserBean>() {
                @Override
                public void done(UserBean userBean, BmobException e) {
                    favariteList = userBean.getFavorite();
                    for (String mylist:favariteList){
                        deletePosition++;
                        if (mylist.equals(url)){
                            favorite_textview.setText("取消收藏");
                            star.setBackgroundResource(R.mipmap.cancelfavorite);
                            return;
                        }
                    }
                }
            });
        }

    }


    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.wallpaper:
                Toast.makeText(Details.this,"壁纸更换成功",Toast.LENGTH_LONG).show();
                try {
                    wallpaperManager = WallpaperManager.getInstance(this);
                    wallpaperManager.setBitmap(imageView_detail.getDrawingCache());


                } catch (IOException e) {
                    e.printStackTrace();

                }



                break;
            case R.id.save:
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        //获取文件夹中文件数量
//                        String filepath = SDCardHelper.getSDCardPublicDir(Environment.DIRECTORY_DOWNLOADS);
//                        getFiles(filepath);
//                        getPosition();
                        String random = createRandom(true, 15);
                        bitmap = HttpURLConnHelper.returnBitmap(url);

                        SDCardHelper.saveBitmapToSDCardPublicDir(bitmap,Environment.DIRECTORY_DOWNLOADS,random+".jpg");

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
//                                imageView_detail.setImageBitmap(bitmap);
                                Toast.makeText(Details.this,"图片保存成功",Toast.LENGTH_LONG).show();
                            }
                        });
                    }
                }).start();
                break;
            case R.id.star:
                loadFavoriteData();
                //获取objectid
                String objectId = PreUtils.readStrting(Details.this, Constants.KEY_OF_OBJECTID);
                if (objectId.equals("8BkXsLLs")){
                    Toast.makeText(this, "请登录", Toast.LENGTH_SHORT).show();
                }else {
                    favariteList = new ArrayList<>();
                    user = new UserBean();
                    String str = favorite_textview.getText().toString();
                    if (str.equals("收藏")){
                        //获取原来收藏的信息
                        BmobQuery<UserBean> query = new BmobQuery<>();
                        query.getObject(objectId, new QueryListener<UserBean>() {
                            @Override
                            public void done(UserBean userBean, BmobException e) {
                                //获取objectid
                                String objectId = PreUtils.readStrting(Details.this, Constants.KEY_OF_OBJECTID);
                                favariteList = userBean.getFavorite();
                                favariteList.add(url);
                                user.setFavorite(favariteList);
                                user.update(objectId, new UpdateListener() {
                                    @Override
                                    public void done(BmobException e) {
                                        Toast.makeText(Details.this, "收藏成功", Toast.LENGTH_SHORT).show();
                                        favorite_textview.setText("取消收藏");
                                        star.setBackgroundResource(R.mipmap.cancelfavorite);
                                    }
                                });
                            }
                        });
                    }else {
                        BmobQuery<UserBean> query = new BmobQuery<>();
                        query.getObject(objectId, new QueryListener<UserBean>() {
                            @Override
                            public void done(UserBean userBean, BmobException e) {
                                String objectId = PreUtils.readStrting(Details.this, Constants.KEY_OF_OBJECTID);
                                favariteList = new ArrayList<>();
                                favariteList = userBean.getFavorite();
                                favariteList.remove(url);
                                user.setFavorite(favariteList);
                                user.update(objectId, new UpdateListener() {
                                    @Override
                                    public void done(BmobException e) {
                                        Toast.makeText(Details.this, "取消收藏成功", Toast.LENGTH_SHORT).show();
                                        favorite_textview.setText("收藏");
                                        star.setBackgroundResource(R.mipmap.favorite);
                                    }
                                });
                            }
                        });

                    }
                }

                break;
            case R.id.share:
                showShare();
                break;
            case R.id.btn_back:
                finish();
                break;
        }

    }
    private void showShare() {
        ShareSDK.initSDK(this,"1915371b11e92");
        hashMap.put("Id","7");
        hashMap.put("SortId","7");
        hashMap.put("AppId","1105825500");
        hashMap.put("AppKey","e6tCxEP7UV30RaYz");
        hashMap.put("Enable","true");
        ShareSDK.setPlatformDevInfo(QQ.NAME,hashMap);
        OnekeyShare oks = new OnekeyShare();

        //关闭sso授权
        oks.disableSSOWhenAuthorize();


        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间等使用
        oks.setTitle("一起来换壁纸吧!");
        // titleUrl是标题的网络链接，QQ和QQ空间等使用
        oks.setTitleUrl("http://mob.com");
        // text是分享文本，所有平台都需要这个字段
        oks.setText("最新的壁纸都在这");
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        oks.setImageUrl(url);

        // oks.setImagePath("/sdcard/zby1.jpg");//确保SDcard下面存在此张图片
        // url仅在微信（包括好友和朋友圈）中使用
//        oks.setUrl("http://sharesdk.cn");
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
//        oks.setComment("我是测试评论文本");
        // site是分享此内容的网站名称，仅在QQ空间使用
//        oks.setSite(getString(R.string.app_name));
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
//        oks.setSiteUrl("http://sharesdk.cn");

        // 启动分享GUI
        oks.show(this);
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        imageView_detail.setDrawingCacheEnabled(false);


    }

    /**
     * 创建指定数量的随机字符串
     * @param numberFlag 是否是数字
     * @param length
     * @return
     */
    public static String createRandom(boolean numberFlag, int length){
        String retStr = "";
        String strTable = numberFlag ? "1234567890" : "1234567890abcdefghijkmnpqrstuvwxyz";
        int len = strTable.length();
        boolean bDone = true;
        do {
            retStr = "";
            int count = 0;
            for (int i = 0; i < length; i++) {
                double dblR = Math.random() * len;
                int intR = (int) Math.floor(dblR);
                char c = strTable.charAt(intR);
                if (('0' <= c) && (c <= '9')) {
                    count++;
                }
                retStr += strTable.charAt(intR);
            }
            if (count >= 2) {
                bDone = false;
            }
        } while (bDone);

        return retStr;
    }
}
